/**
 * 研发项目业务逻辑
 */

const ResearchStateMachine = require('../../store/modules/research/research_state_machine');
const ResearchPhaseConfig = require('../../config/research_phase_config');
const ResearchRoleConfig = require('../../config/research_role_config');
const pageHelper = require('../../config/project_helpers_config').pageHelper;
const cloudHelper = require('../../config/project_helpers_config').cloudHelper;
const ProjectBiz = require('./project_biz.js');
const timeHelper = require('../../config/project_helpers_config').timeHelper;
const projectHelper = require('../../config/project_helpers_config').projectHelper;
const dataHelper = require('../../config/project_helpers_config').dataHelper;
const cacheHelper = require('../../config/project_helpers_config').cacheHelper;
const bizHelper = require('../../config/biz_config').baseBiz;
const validate = require('../../config/project_helpers_config').validate;
const dateHelper = require('../../config/project_helpers_config').dateHelper;
const dayjs = require('../../config/libs_config').dayjs;

// 缓存相关
const CACHE_RESEARCH_LIST = 'CACHE_OA_RESEARCH_LIST';
const CACHE_RESEARCH_DETAIL = 'CACHE_OA_RESEARCH_DETAIL_'; // 项目详情缓存前缀
const CACHE_CURRENT_ID = 'CURRENT_RESEARCH_ID'; // 当前项目ID缓存键
const CACHE_TIME = 30 * 60 * 1000; // 30分钟缓存

/**
 * 根据状态获取研发阶段
 * @param {String} state 状态
 * @returns {String} 阶段代码
 */
function getPhaseByState(state) {
  return ResearchPhaseConfig.getCurrentPhase(state);
}

/**
 * 获取研发阶段名称
 * @param {String} phase 阶段代码
 * @returns {String} 阶段名称
 */
function getPhaseName(phase) {
  return ResearchPhaseConfig.getPhaseName(phase);
}

/**
 * 获取状态名称
 * @param {String} state 状态代码
 * @returns {String} 状态名称
 */
function getStateName(state) {
  return ResearchStateMachine.getStateName(state);
}

/**
 * 获取状态描述
 * @param {String} state 状态代码
 * @returns {String} 状态描述
 */
function getStateDesc(state) {
  // 如果状态机定义中有描述字段则使用，否则使用状态名称
  return ResearchStateMachine.getStateName(state); // 暂时使用名称代替描述
}

/**
 * 获取状态颜色
 * @param {String} state 状态代码
 * @returns {String} 状态颜色
 */
function getStateColor(state) {
  return ResearchStateMachine.getStateColor(state);
}

/**
 * 获取事件名称
 * @param {String} event 事件代码
 * @returns {String} 事件名称
 */
function getEventName(event) {
  return ResearchStateMachine.getEventName(event);
}

/**
 * 获取当前状态可用事件
 * @param {String} stateCode 状态代码
 * @param {Array|String} userRole 用户角色
 * @returns {Array} 可用事件列表
 */
function getAvailableEvents(stateCode, userRole = ['developer']) {
  if (!stateCode) return [];
  
  const events = ResearchStateMachine.getAvailableEvents(stateCode);
  
  // 根据用户角色过滤
  // 这里可以结合ResearchRoleConfig进行权限过滤
  // TODO: 实现角色权限过滤
  
  return events;
}

/**
 * 检查事件是否有效
 * @param {String} stateCode 状态代码
 * @param {String} eventId 事件代码
 * @returns {Boolean} 是否有效
 */
function isValidEvent(stateCode, eventId) {
  return ResearchStateMachine.isEventAvailable(stateCode, eventId);
}

/**
 * 获取目标状态
 * @param {String} stateCode 当前状态
 * @param {String} eventId 事件代码
 * @returns {String} 目标状态
 */
function getTargetState(stateCode, eventId) {
  return ResearchStateMachine.getNextState(stateCode, eventId);
}

/**
 * 获取所有状态
 * @returns {Array} 状态列表
 */
function getAllStates() {
  return Object.keys(ResearchStateMachine.STATES).map(code => ({
    code,
    name: ResearchStateMachine.getStateName(code),
    color: ResearchStateMachine.getStateColor(code)
  }));
}

/**
 * 获取所有事件
 * @returns {Array} 事件列表
 */
function getAllEvents() {
  return Object.keys(ResearchStateMachine.EVENTS).map(code => ({
    id: code,
    name: ResearchStateMachine.getEventName(code)
  }));
}

/**
 * 检查阶段文档完成情况
 * @param {Object} project 项目信息
 * @returns {Object} 文档完成情况，格式 {total, completed, percentage}
 */
function checkPhaseDocsCompletion(project) {
  if (!project || !project.state) return { total: 0, completed: 0, percentage: 0 };
  
  const phase = getPhaseByState(project.state);
  return ResearchPhaseConfig.checkPhaseDocsCompletion(project.docs || [], phase);
}

/**
 * 获取项目所需文档
 * @param {Object} project 项目信息
 * @returns {Array} 文档列表，格式 [{type, name, description, required, completed}]
 */
function getProjectRequiredDocs(project) {
  if (!project || !project.state) return [];
  
  const phase = getPhaseByState(project.state);
  const requiredDocs = ResearchPhaseConfig.getPhaseRequiredDocs(phase);
  
  // 检查文档是否已完成
  const projectDocs = project.docs || [];
  
  return requiredDocs.map(doc => {
    const completed = projectDocs.some(projectDoc => 
      projectDoc.type === doc.type && projectDoc.status === 'completed'
    );
    
    return {
      ...doc,
      completed
    };
  });
}

/**
 * 触发状态转换事件
 * @param {String} projectId 项目ID
 * @param {String} event 事件代码
 * @param {Object} data 附加数据
 * @returns {Promise} 请求结果
 */
async function triggerEvent(projectId, event, data = {}) {
  try {
    const params = {
      projectId,
      event,
      data
    };
    
    const result = await cloudHelper.callCloudSumbit('research/trigger', params);
    return result;
  } catch (err) {
    console.error('[研发项目] 触发事件失败', err);
    throw err;
  }
}

/**
 * 上传研发文档
 * @param {String} projectId 项目ID
 * @param {String} docType 文档类型
 * @param {Object} fileData 文件数据
 * @param {String} description 文档描述
 * @returns {Promise} 请求结果
 */
async function uploadProjectDoc(projectId, docType, fileData, description = '') {
  try {
    // 上传文件
    const cloud = wx.cloud;
    const timestamp = dateHelper().format('YYYY-MM-DD-HH-mm-ss');
    const filePath = `research/${projectId}/${docType}_${timestamp}`;
    
    const uploadRes = await cloud.uploadFile({
      cloudPath: filePath,
      filePath: fileData.path,
    });
    
    if (!uploadRes || !uploadRes.fileID) {
      throw new Error('文件上传失败');
    }
    
    // 提交文档信息
    const params = {
      projectId,
      docType,
      fileId: uploadRes.fileID,
      fileName: fileData.name,
      description,
      timestamp: dateHelper().valueOf()
    };
    
    const result = await cloudHelper.callCloudSumbit('research/upload_doc', params);
    return result;
  } catch (err) {
    console.error('[研发项目] 上传文档失败', err);
    throw err;
  }
}

/**
 * 获取项目进度信息
 * @param {Object} project 项目信息
 * @returns {Object} 进度信息，格式 {currentPhase, phaseName, progress, docsCompletion}
 */
function getProjectProgress(project) {
  if (!project || !project.state) {
    return {
      currentPhase: null,
      phaseName: '',
      progress: 0,
      docsCompletion: { total: 0, completed: 0, percentage: 0 }
    };
  }
  
  const currentPhase = getPhaseByState(project.state);
  const phases = ResearchPhaseConfig.getAllPhases();
  const currentPhaseIndex = phases.findIndex(phase => phase.code === currentPhase);
  
  // 计算总体进度
  const progress = Math.round((currentPhaseIndex + 1) / phases.length * 100);
  
  // 文档完成情况
  const docsCompletion = checkPhaseDocsCompletion(project);
  
  return {
    currentPhase,
    phaseName: getPhaseName(currentPhase),
    progress,
    docsCompletion
  };
}

/**
 * 获取项目发起人信息
 * @param {Object} project 项目信息
 * @returns {Object} 发起人信息，格式 {name, avatar, dept}
 */
function getProjectCreator(project) {
  if (!project || !project.USER_DETAIL) {
    return { name: '', avatar: '', dept: '' };
  }
  
  const userDetail = project.USER_DETAIL;
  
  return {
    name: userDetail.USER_NAME || '',
    avatar: userDetail.USER_PIC || '',
    dept: userDetail.dept || ''
  };
}

/**
 * 获取项目状态图标
 * @param {String} state 状态代码
 * @returns {String} 图标类名
 */
function getStateIcon(state) {
  return ResearchStateMachine.getStateIcon(state);
}

/**
 * 从缓存中获取项目列表
 * @returns {Object|null} 项目列表数据，包含list和isAllLoaded字段，如果缓存不存在或已过期则返回null
 */
function getProjectListFromCache() {
	try {
		const cacheData = cacheHelper.get(CACHE_RESEARCH_LIST);
		
		// 检查缓存是否存在且格式正确
		if (!cacheData) {
			console.warn('[研发项目] 缓存不存在或已过期');
			return null;
		}
		
		// 检查缓存数据格式
		if (!cacheData.list || !Array.isArray(cacheData.list)) {
			console.warn('[研发项目] 缓存数据格式不正确');
			return null;
		}
		
		console.log(`[研发项目] 从缓存获取到${cacheData.list.length}条项目数据`);
		return cacheData;
	} catch (e) {
		console.error('[研发项目] 读取缓存失败', e);
		return null;
	}
}

/**
 * 设置项目列表缓存
 * @param {Object} cacheData 包含list和isAllLoaded字段的对象
 */
function setProjectListCache(cacheData) {
	try {
		// 校验参数
		if (!cacheData || !cacheData.list || !Array.isArray(cacheData.list)) {
			console.warn('[研发项目] 缓存数据格式不正确，无法缓存');
			return;
		}
  
		// 设置缓存
		cacheHelper.set(CACHE_RESEARCH_LIST, cacheData, CACHE_TIME);
		console.log(`[研发项目] 已缓存${cacheData.list.length}条项目数据`);
	} catch (e) {
		console.error('[研发项目] 设置缓存失败', e);
	}
}

/**
 * 清除项目列表缓存
 */
function clearProjectListCache() {
	try {
		cacheHelper.remove(CACHE_RESEARCH_LIST);
		console.log('[研发项目] 已清除项目列表缓存');
	} catch (e) {
		console.error('[研发项目] 清除缓存失败', e);
	}
}

/**
 * 获取当前正在查看的研发项目ID
 * @returns {String} 项目ID
 */
function getCurrentId() {
  // 优先从缓存中获取
  let currentId = cacheHelper.get(CACHE_CURRENT_ID);
  
  // 尝试从全局变量获取
  if (!currentId) {
    try {
      const app = getApp();
      if (app && app.globalData && app.globalData.currentResearchId) {
        currentId = app.globalData.currentResearchId;
      }
    } catch (err) {
      console.warn('[研发项目] 从全局变量获取当前ID失败', err);
    }
  }
  
  return currentId || '';
}

/**
 * 设置当前正在查看的研发项目ID
 * @param {String} id 项目ID
 */
function setCurrentId(id) {
  if (!id) return;
  
  // 保存到缓存
  cacheHelper.set(CACHE_CURRENT_ID, id, CACHE_TIME);
  
  // 同时保存到全局变量
  try {
    const app = getApp();
    if (app && app.globalData) {
      app.globalData.currentResearchId = id;
    }
  } catch (err) {
    console.warn('[研发项目] 保存ID到全局变量失败', err);
  }
  
  console.log('[研发项目] 当前项目ID已设置:', id);
}

/**
 * 健壮的项目详情加载
 * @param {String} id 项目ID
 * @param {Boolean} useCache 是否使用缓存
 * @returns {Promise<Object>} 项目详情
 */
async function loadProjectDetail(id, useCache = true) {
  if (!id) {
    console.error('[研发项目] 加载详情失败: ID为空');
    throw new Error('项目ID不能为空');
  }
  
  try {
    // 检查缓存
    if (useCache) {
      const cachedProject = getProjectDetailFromCache(id);
      if (cachedProject) {
        console.log('[研发项目] 从缓存加载项目详情:', id);
        return cachedProject;
      }
    }
    
    // 调用云函数
    console.log('[研发项目] 从服务器加载项目详情:', id);
    let project = null;
    
    try {
      // 尝试第一种API
      project = await cloudHelper.callCloudData('research_project/detail', { id });
    } catch (err) {
      console.warn('[研发项目] 第一种API调用失败，尝试备用API:', err);
      
      // 尝试备用API
      project = await cloudHelper.callCloudData('research/detail', { id });
    }
    
    if (!project) {
      throw new Error('项目不存在或已被删除');
    }
    
    // 缓存项目详情
    setProjectDetailCache(id, project);
    
    return project;
  } catch (err) {
    console.error('[研发项目] 加载项目详情失败:', err);
    throw err;
  }
}

/**
 * 获取模拟项目列表
 * @param {Object} params 查询参数
 * @returns {Array} 模拟项目列表
 */
function getMockProjectList(params = {}) {
	try {
		// 模拟10个项目数据
		let mockList = [];
		for (let i = 1; i <= 10; i++) {
			// 随机状态
			const statusIndex = Math.floor(Math.random() * RESEARCH_STATUS_OPTIONS.length);
			const statusId = RESEARCH_STATUS_OPTIONS[statusIndex].id;
			
			// 随机类型
			const typeIndex = Math.floor(Math.random() * PROJECT_CATE_OPTIONS.length);
			const typeId = PROJECT_CATE_OPTIONS[typeIndex].id;
			
			// 创建模拟项目数据
			mockList.push({
				_id: `mock_${i}`,
				PROJECT_TITLE: `模拟项目 ${i}`,
				PROJECT_CODE: `PROJ${String(i).padStart(4, '0')}`,
				PROJECT_STATUS: statusId,
				PROJECT_CATE: typeId,
				PROJECT_OBJ: '这是一个模拟项目，用于测试展示',
				PROJECT_DESC: '模拟项目详细描述，包含项目背景、目标、范围等',
				PROJECT_START: dayjs().subtract(10, 'day').format('YYYY-MM-DD'),
				PROJECT_END: dayjs().add(30, 'day').format('YYYY-MM-DD'),
				PROJECT_MANAGER: {
					USER_NAME: `项目经理${i}`,
					USER_ID: `mockuser_${i}`
				},
				PROJECT_MEMBER: [
					{
						USER_NAME: `成员A${i}`,
						USER_ID: `mockmember_a${i}`
					},
					{
						USER_NAME: `成员B${i}`,
						USER_ID: `mockmember_b${i}`
					}
				],
				ADD_TIME: dayjs().subtract(10, 'day').valueOf(),
				EDIT_TIME: dayjs().subtract(2, 'day').valueOf()
			});
		}
		
		// 根据搜索条件过滤
		if (params.search) {
			const keyword = params.search.toLowerCase();
			mockList = mockList.filter(item => {
				return item.PROJECT_TITLE.toLowerCase().includes(keyword) || 
					item.PROJECT_CODE.toLowerCase().includes(keyword) || 
					item.PROJECT_OBJ.toLowerCase().includes(keyword);
			});
		}
		
		// 根据状态过滤
		if (params.status && params.status !== 'all') {
			mockList = mockList.filter(item => item.PROJECT_STATUS === params.status);
		}
		
		// 根据类型过滤
		if (params.cate && params.cate !== '') {
			mockList = mockList.filter(item => item.PROJECT_CATE === params.cate);
		}
		
		return {
			code: 200,
			data: {
				list: mockList,
				total: mockList.length,
				size: mockList.length,
				page: 1,
				hasMore: false
			}
		};
	} catch (e) {
		console.error('[研发项目] 生成模拟数据失败', e);
		return {
			code: 500,
			message: '生成模拟数据失败'
		};
	}
}

/**
 * 从缓存中获取项目详情
 * @param {String} id 项目ID
 * @returns {Object|null} 项目详情，如果缓存不存在或已过期则返回null
 */
function getProjectDetailFromCache(id) {
  if (!id) return null;
  
  try {
    const cacheKey = CACHE_RESEARCH_DETAIL + id;
    const cacheData = cacheHelper.get(cacheKey);
    
    // 检查缓存是否存在
    if (!cacheData) {
      console.warn(`[研发项目] 项目详情缓存不存在或已过期: ${id}`);
      return null;
    }
    
    console.log(`[研发项目] 从缓存获取项目详情: ${id}`);
    return cacheData;
  } catch (e) {
    console.error('[研发项目] 读取项目详情缓存失败', e);
    return null;
  }
}

/**
 * 设置项目详情缓存
 * @param {String} id 项目ID
 * @param {Object} project 项目详情
 */
function setProjectDetailCache(id, project) {
  if (!id || !project) return;
  
  try {
    const cacheKey = CACHE_RESEARCH_DETAIL + id;
    
    // 设置缓存
    cacheHelper.set(cacheKey, project, CACHE_TIME);
    console.log(`[研发项目] 已缓存项目详情: ${id}`);
  } catch (e) {
    console.error('[研发项目] 设置项目详情缓存失败', e);
  }
}

/**
 * 清除项目详情缓存
 * @param {String} id 项目ID，如不指定则清除所有项目详情缓存
 */
function clearProjectDetailCache(id) {
  try {
    if (id) {
      // 清除指定项目缓存
      const cacheKey = CACHE_RESEARCH_DETAIL + id;
      cacheHelper.remove(cacheKey);
      console.log(`[研发项目] 已清除项目详情缓存: ${id}`);
    } else {
      // 获取所有缓存键
      const keys = cacheHelper.getAllKeys();
      // 过滤出项目详情缓存键
      const detailKeys = keys.filter(key => key.startsWith(CACHE_RESEARCH_DETAIL));
      // 清除所有项目详情缓存
      detailKeys.forEach(key => cacheHelper.remove(key));
      console.log(`[研发项目] 已清除所有项目详情缓存: ${detailKeys.length}个`);
    }
  } catch (e) {
    console.error('[研发项目] 清除项目详情缓存失败', e);
  }
}

// 导出所有业务方法
module.exports = {
  // 从状态机导出的常量
  STATES: ResearchStateMachine.STATES,
  EVENTS: ResearchStateMachine.EVENTS,

  // 状态相关
  getStateName,
  getStateDesc,
  getStateColor,
  getStateIcon,
  
  // 事件相关
  getEventName,
  getAvailableEvents,
  isValidEvent,
  getTargetState,
  getAllStates,
  getAllEvents,
  
  // 新增方法：获取当前用户的项目列表
  getMyProjects: async function(params = {}) {
    try {
      // 设置默认参数
      const defaultParams = {
        page: 1,
        size: 20,
        search: '',
        sortType: '',
        sortVal: '',
        status: '',
        cate: ''
      };
      
      // 合并参数
      const queryParams = {...defaultParams, ...params};
      console.log('[ResearchBiz] getMyProjects 请求参数:', queryParams);
      
      // 如果请求缓存
      if (queryParams.cacheKey && queryParams.cacheTime) {
        const cachedData = getProjectListFromCache();
        if (cachedData) {
          console.log('[ResearchBiz] 使用缓存数据，跳过API调用');
          return {
            list: cachedData.list || [],
            total: cachedData.total || 0,
            has_more: cachedData.has_more || false
          };
        }
      }
      
      // 尝试直接调用research_project/list接口
      let result;
      try {
        console.log('[ResearchBiz] 调用research_project/list接口');
        result = await cloudHelper.callCloudData('research_project/list', queryParams);
      } catch (err) {
        console.error('[ResearchBiz] research_project/list接口调用失败:', err);
        
        // 尝试调用备用接口
        console.log('[ResearchBiz] 调用备用接口research/list');
        result = await cloudHelper.callCloudData('research/list', queryParams);
      }
      
      // 处理结果
      if (result) {
        console.log('[ResearchBiz] API返回数据');
        
        // 处理可能的不同数据结构
        let dataList, total, hasMore;
        
        if (result.list) {
          // 标准结构
          dataList = result.list;
          total = result.total;
          hasMore = result.has_more;
        } else if (result.data && result.data.list) {
          // 嵌套在data中的结构
          dataList = result.data.list; 
          total = result.data.total;
          hasMore = false; // 保守设置为false
        } else {
          // 未知结构，设为空
          console.warn('[ResearchBiz] 未知的API返回结构:', result);
          dataList = [];
          total = 0;
          hasMore = false;
        }
        
        // 确保每个项目都有必要的字段
        const processedList = dataList.map(item => {
          // 保证标题字段
          if (!item.PROJECT_TITLE && !item.RESEARCH_TITLE) {
            item.PROJECT_TITLE = item.title || '未命名项目';
          }
          
          // 保证状态字段
          if (item.PROJECT_STATUS === undefined || item.PROJECT_STATUS === null) {
            item.PROJECT_STATUS = 1; // 默认为"规划中"
          }
          
          return item;
        });
        
        // 如果需要缓存结果
        if (queryParams.cacheKey) {
          setProjectListCache({
            list: processedList,
            total: total,
            has_more: hasMore
          });
          console.log('[ResearchBiz] 已缓存项目列表数据');
        }
        
        return {
          list: processedList,
          total: total,
          has_more: hasMore
        };
      }
      
      console.warn('[ResearchBiz] API无返回值');
      return { list: [], total: 0, has_more: false };
    } catch (err) {
      console.error('[研发项目] 获取项目列表失败:', err);
      throw err;
    }
  },
  
  // 阶段相关
  getPhaseByState,
  getPhaseName,
  
  // 文档相关
  checkPhaseDocsCompletion,
  getProjectRequiredDocs,
  uploadProjectDoc,
  
  // 项目信息
  getProjectProgress,
  getProjectCreator,
  triggerEvent,
  
  // 缓存
  getProjectListFromCache,
  setProjectListCache,
  clearProjectListCache,
  getProjectDetailFromCache,
  setProjectDetailCache,
  clearProjectDetailCache,
  
  // 新增导出
  getCurrentId,
  setCurrentId,
  loadProjectDetail,
  
  // 新增模拟数据方法
  getMockProjectList
}; 